//
//  ViewController.m
//  QQ聊天界面
//
//  Created by 3tee on 2021/6/7.
//  Copyright © 2021年 3tee. All rights reserved.
//

#import "AVDChatVC.h"
#import "ZQJMessage.h"
#import "ZQJMessageFrame.h"
#import "ZQJMessageCell.h"

@interface AVDChatVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,AVDChatDelegate>

@property (nonatomic, strong) NSMutableArray *messageFrames;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *inputTF;
@property (nonatomic, strong) AVDChat *mchat;

@end

@implementation AVDChatVC

- (void)dealloc{
    NSLog(@"AVDChatVC dealloc");
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}


- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSString *roomid = [[NSUserDefaults standardUserDefaults] stringForKey:roomIdKey];
    AVDRoom *room = [AVDRoom obtain:roomid];
    self.mchat = [AVDChat getChat:room];
    self.mchat.delegate = self;
    [self setupUI];
}



- (void)setupUI{
    self.title = @"聊天";
    self.inputTF.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (NSMutableArray *)messageFrames{
    if (!_messageFrames) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"message.plist" ofType:nil];
        NSArray *arr = [NSArray arrayWithContentsOfFile:path];
        NSMutableArray *frameModels = [NSMutableArray array];
        ZQJMessage *lastMessage;
        for (NSDictionary *dic in arr) {
            ZQJMessage *message = [ZQJMessage messageWithDic:dic];
            if ([message.time isEqualToString:lastMessage.time]) {
                message.isHidenTime = YES;
            }
            ZQJMessageFrame *frame = [[ZQJMessageFrame alloc]init];
            frame.message = message;
            lastMessage = message;
            [frameModels addObject:frame];
        }
        _messageFrames = frameModels;
    }
    return _messageFrames;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.messageFrames.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"message_cell";
    ZQJMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (nil == cell) {
        cell = [[ZQJMessageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    cell.msgFrame = _messageFrames[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZQJMessageFrame *frameMes = _messageFrames[indexPath.row];
    //NSLog(@"rowH === %f",frameMes.rowHeight);
    return frameMes.rowHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//监听键盘弹出高度
- (void)keyboardFrameChanged:(NSNotification *)noti{
    //NSLog(@"keyboard changeFrame = %@",noti);
    //获取键盘弹出或者隐藏之后的Y值
    CGRect keyboardRect = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardY = keyboardRect.origin.y;
    CGFloat viewOffset = keyboardY - self.view.frame.size.height;
    [UIView animateWithDuration:0.25 animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, viewOffset);
    }];
    if(self.messageFrames.count > 1){
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messageFrames.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self sendMsg];
    return YES;
}

- (IBAction)sendClicked:(UIButton *)sender {
    [self sendMsg];
}


- (void)sendMsg{
    NSString *inputText = self.inputTF.text;
    AVDResult ret = [self.mchat sendPublicMessage:inputText];
    if(ret == AVD_Success){
        [self addMsg:inputText type:ZQJMessageMe time:[NSDate date] name:[self.mchat.usermanager getSelfUserName]];
        self.inputTF.text = nil;
    }else{
        [self toastMsg:@"消息发送失败，请重新发送"];
    }
}

- (void)addMsg:(NSString *)mg type:(ZQJMessageType)type time:(NSDate *)msgTime name:(NSString *)name{
    //创建一个message messageFrame
    ZQJMessage *msg = [[ZQJMessage alloc]init];
    msg.name = name;
    msg.type = type;
    msg.msg = mg;
    NSDate *curDate = msgTime;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"今天 HH:mm";
    NSString *time = [dateFormatter stringFromDate:curDate];
    //获取上一条消息时间
    ZQJMessageFrame *lastMsg = [self.messageFrames lastObject];
    if ([lastMsg.message.time isEqualToString:time]) {
        msg.isHidenTime = YES;
    }
    msg.time = time;
    ZQJMessageFrame *msgFrame = [[ZQJMessageFrame alloc]init];
    msgFrame.message = msg;
    [self.messageFrames addObject:msgFrame];
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messageFrames.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

#pragma mark - AVDChatDelegate
- (void)onPublicMessage:(AVDMessage *)message{
    [self addMsg:message.message type:ZQJMessageOther time:message.timestamp name:message.fromName];
}

- (void)onPrivateMessage:(AVDMessage *)message{
    [self addMsg:message.message type:ZQJMessageOther time:message.timestamp name:message.fromName];
}

- (void)toastMsg:(NSString *)msg{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.label.text = msg;
    hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
    [hud hideAnimated:YES afterDelay:2.f];
}


@end
